/**
 * ProtoActor TypeScript SDK 简单示例
 * 
 * 此示例展示了如何使用 TypeScript SDK 创建和使用 Actor
 * 运行方式: bun run example:simple-actor
 */

import { Actor, fromFunc } from '../actor/actor';
import { Context } from '../actor/context';
import { Props } from '../actor/props';
import { PID } from '../actor/pid';
import { RootContext } from '../actor/rootContext';
import { ActorSystem } from '../actor/actorSystem';

// 定义消息类型
interface HelloMessage {
  name: string;
}

interface GoodbyeMessage {
  name: string;
}

// 定义一个简单的 Actor
class GreetingActor implements Actor {
  constructor(private name: string) {}

  async receive(context: Context): Promise<void> {
    const message = context.message();  // 注意这里需要是一个函数调用
    
    // 调试消息类型
    console.log(`[${this.name}] 收到消息类型: ${typeof message}`, message);
    
    // 处理不同类型的消息
    if (this.isHelloMessage(message)) {
      console.log(`[${this.name}] 收到问候: 你好, ${message.name}!`);
      // 回复一个 Goodbye 消息
      const sender = context.sender();
      if (sender) {  // 检查sender是否存在
        await context.send(sender, { name: this.name } as GoodbyeMessage);
      }
    }
    else if (this.isGoodbyeMessage(message)) {
      console.log(`[${this.name}] 收到告别: 再见, ${message.name}!`);
    }
    else {
      console.log(`[${this.name}] 收到未知消息:`, message);
    }
  }

  // 类型守卫
  private isHelloMessage(message: any): message is HelloMessage {
    return message && typeof message === 'object' && 'name' in message;
  }

  private isGoodbyeMessage(message: any): message is GoodbyeMessage {
    return message && typeof message === 'object' && 'name' in message;
  }
}

// 运行示例
async function runExample() {
  console.log('===== ProtoActor TypeScript 简单示例 =====\n');

  // 创建 Actor System
  const system = new ActorSystem();
  
  // 创建 Root Context
  const context = new RootContext(system);

  try {
    // 创建第一个 Actor
    const props1 = Props.fromProducer(() => new GreetingActor('Actor1'));
    const pid1 = await context.spawnNamed(props1, 'actor1');
    console.log('创建了 Actor1:', pid1);

    // 创建第二个 Actor
    const props2 = Props.fromProducer(() => new GreetingActor('Actor2'));
    const pid2 = await context.spawnNamed(props2, 'actor2');
    console.log('创建了 Actor2:', pid2);

    // 让 Actor1 向 Actor2 发送消息
    console.log('\n--- Actor1 向 Actor2 发送 Hello ---');
    await context.send(pid2, { name: 'Actor1' } as HelloMessage);

    // 等待一会儿以便看到消息处理
    await new Promise(resolve => setTimeout(resolve, 100));

    // 让 Actor2 向 Actor1 发送消息
    console.log('\n--- Actor2 向 Actor1 发送 Hello ---');
    await context.send(pid1, { name: 'Actor2' } as HelloMessage);

    // 等待一会儿以便看到消息处理
    await new Promise(resolve => setTimeout(resolve, 100));

    // 停止 Actor
    console.log('\n--- 停止 Actor ---');
    await context.stop(pid1);
    await context.stop(pid2);

    console.log('\n示例运行完成!');

  } catch (error) {
    console.error('示例运行出错:', error);
  }
}

// 运行示例
runExample().catch(console.error); 